<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\company\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;

/**
 * 部门管理
 * Class User
 * @package app\worker\controller
 */
class Department extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    // protected $table = 'CompanyUser';
	protected $table = 'CompanyUserDepartment';
    protected $table_dept = 'dept';
	protected $table_department = 'SystemMenu';
    protected $table_view_department = 'view_company_dept';
    /**
     * 部门列表
     * @auth true
     * @menu true
     * @throws \think\Exception
	 
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {

        $where ='';
        $uinfo = $this->getGuserinfo();
        switch ($uinfo['db1']['authorize']) {
            case '1':
                break;
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '8':
                $where = 'companyid = '.$uinfo['db2']['companyid'];
                # code...
                break;
            default:
                $this->error('无权限访问');
                # code...
                break;
        }



        $this->title = '部门管理';
		$create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
		$create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';
	    $dbconf = $this->getconfig('vister_db');

        if($this->request->param('company_id')){
            $company_info = Db::connect($dbconf)->table('view_company')->where('id = '.$this->request->param('company_id'))->find();
            $this->title = $company_info['name'].'-部门管理';
            $where = 'companyid = '.$this->request->param('company_id');
        }
			 if(!$create_at_first||!$create_at_last){
                 if($this->request->param('ajax')){
                  $res= Db::connect($dbconf)->table('view_company_dept')->where($where)->order('createtime desc')->select();
			      $this->success('成功',$res,200);
              }
				  $this->_query(Db::connect($dbconf)->table('view_company_dept'))->where($where)->like('dept_name,name')->equal('status')->order('createtime desc')->page();
			
				}
				else{
                     if($this->request->param('ajax')){
                $res = Db::connect($dbconf)->table('view_company_dept')
                                                        ->where($where)
                                                        ->where('createtime','between',[$create_at_first,$create_at_last])
                                                        ->order('createtime desc')
                                                        ->select();
                 $this->success('成功',$res,200);
             }
				 $this->_query(Db::connect($dbconf)->table('view_company_dept'))
                                                        ->where($where)
				                                        ->where('createtime','between',[$create_at_first,$create_at_last])
                                                        ->like('dept_name,name')
                                                        ->equal('status')
                                                        ->order('createtime desc')
														->page();
														
			}
		
    }

	public function index_search()
	{
		 // $this->_query($this->table)->like('nickname,svn_username,department')->equal('status')->page();
		// $list=Db::name('CompanyUserDepartment')->order('id')->select();
		//   $this->assign('list',$list);
		//   return $this->fetch();
	}
    /**
     * 添加部门
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        //$this->title = '添加部门';
		$dbconf = $this->getconfig('vister_db');
        $company_list = Db::connect($dbconf)->table('view_company')->select();
        $this->assign('data',[
            /**丢给视图的数据**/
            'companylist'=>$company_list,

        ]);
        $this->assign('vo',['id'=>NULL,'start_time'=>NULL,'end_time'=>NULL]);
        if($this->request->isPost()){
            $name = $this->request->param('department');
            $companyid = $this->request->param('companyid');
            $dept_manager_userid = $this->request->param('dept_manager_userid')?:NULL;
            $scheduling_first = $this->request->param('scheduling_first');
            $scheduling_last = $this->request->param('scheduling_last');
            $address = $this->request->param('address');
            $address_imglist = $this->request->param('dept_logo');

            $where ='';
            $uinfo = $this->getGuserinfo();
            //var_dump($uinfo);
            switch ($uinfo['db1']['authorize']) {
                case '1':
                    # code...
                    $where = 'name like "'.$name.'" and companyid = '.$companyid;
                    break;
                case '2':
                case '8':
                    $companyid = $uinfo['db2']['companyid'];
                    $where = 'name like "'.$name.'" and companyid = '.$companyid;
                    # code...
                    break;
                default:
                    # code...
                    break;
            }
            //转换图片为json 字符串
            if($address_imglist){
              
              $new_list = explode("|", $address_imglist);
              $new_list_str = json_encode($new_list,JSON_UNESCAPED_SLASHES);
            }else{
              $new_list_str = '';
            }
            $data = [
                'name' => $name,
                'companyid' => $companyid,
                'createtime' => time(),
                'address' =>$address,
                'address_image'=>$new_list_str,
            ];
            $data['status'] = $this->request->param('status')=="on"?1:0;
            $data['status']= 1;
            $data['is_security'] = $this->request->param('is_security')=="on"?1:0;
            $check = Db::connect($dbconf)->table($this->table_dept)->where($where)->find();

            if($check){$this->error('部门已存在','');}
            if($data['is_security']==1){
                $check = Db::connect($dbconf)->table($this->table_dept)->where('companyid ='.$companyid.' and is_security = 1')->find();
                if($check){return $this->error('已存在门卫部门,请设置唯一门卫部门','');}
            }
            $dept_in = Db::connect($dbconf)->table($this->table_dept)->insertGetId($data);

            //设置部门经理
            if($dept_manager_userid){
                $res = Db::connect($dbconf)->table('user')->where('id = '.$dept_manager_userid)
                                                          ->data(['companyid'=>$companyid,'deptid'=>$dept_in,'roleid'=>3])
                                                          ->update();
            }
            //设置部门排班
            if($scheduling_first && $scheduling_last){
                $data =  [
                    'start_time' => $scheduling_first,
                    'end_time' => $scheduling_last,
                    'deptid' => $dept_in,
                    'createtime' => time(),
                ];
                $res  = Db::connect($dbconf)->table('scheduling')->insert($data);
            }
            $this->redirect('index');
            $this->success('添加部门成功','');

        }


       $this->_form(Db::connect($dbconf)->table($this->table_view_department), 'form');
    }


    /**
     * 修改部门信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {

        $dbconf = $this->getconfig('vister_db');
        $companyid = $this->request->param('companyid');
        $dept_id = $this->request->param('id');
        $company_list = Db::connect($dbconf)->table('view_company')->select();
        $company_user_list = Db::connect($dbconf)->table('view_user')->where('companyid = '.$companyid)->select();
        $manager_info = Db::connect($dbconf)->table('view_user')->where('companyid = '.$companyid.' and deptid = '.$dept_id.' and roleid = 3')->find();
        $this->assign('data',[
            /**丢给视图的数据**/
            'companylist'=>$company_list,
            'company_user_list' => $company_user_list,
            'manager_info' => $manager_info,

        ]);
        
        //exit();
        if($this->request->isPost()){

            $name = $this->request->param('department');
            $companyid = $this->request->param('companyid');
            $scheduling_first = $this->request->param('scheduling_first')?:'09:00:00';
            $scheduling_last = $this->request->param('scheduling_last')?:'18:00:00';
            $address = $this->request->param('address');
            $address_imglist = $this->request->param('dept_logo');

            if(!$companyid){$this->error('参数不全','');}
            //转换图片为json 字符串
            if($address_imglist){
              
              $new_list = explode("|", $address_imglist);
              $new_list_str = json_encode($new_list,JSON_UNESCAPED_SLASHES);
            }else{
              $new_list_str = '';
            }
            $data = [
                'name' => $name,
                'companyid' => $companyid,
                'address' =>$address,
                'address_image'=>$new_list_str,
            ];
            $data['status'] = $this->request->param('status')=="on"?1:0;
            $data['is_security'] = $this->request->param('is_security')=="on"?1:0;

            $where = ['id'=>$this->request->param('id')];

            if($data['is_security']==1){
                $check = Db::connect($dbconf)->table($this->table_dept)->where('companyid ='.$companyid.' and is_security = 1')->find();
                if($check){return $this->error('已存在门卫部门,请设置唯一门卫部门','');}
            }
            //设置部门排班
            if($scheduling_first && $scheduling_last){
                $dept_scheduling_info = Db::connect($dbconf)->table('view_dept_scheduling')->where('deptid = '.$dept_id)->find();
                if($dept_scheduling_info){
                    $data_scheduling =  [
                        'start_time' => $scheduling_first,
                        'end_time' => $scheduling_last,
                    ];
    
                    $res  = Db::connect($dbconf)->table('scheduling')->where('deptid = '.$dept_id)->data($data_scheduling)->update();
                }else{
                    //没有则插入

                        $scheduling_data = [
                            'deptid' => $dept_id,
                            'start_time' => $scheduling_first,
                            'end_time' => $scheduling_last,
                            'createtime' => time(),
                        ];
                        $res  = Db::connect($dbconf)->table('scheduling')->insert($scheduling_data);
    
               
                }



            }
            
            $this->_save(Db::connect($dbconf)->table($this->table_dept), $data, $field = '', $where);
        }
        $this->_form(Db::connect($dbconf)->table($this->table_view_department), 'form');
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    // protected function _form_filter(&$data)
    // {
    //     var_dump($data);
    // }

    /**
     * 更改部门状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
        $dbconf = $this->getconfig('vister_db');
        $this->_save(Db::connect($dbconf)->table($this->table_dept), ['status' => $this->request->param('status')]);
    }

    /**
     * 删除企业部门
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        // $this->_delete($this->table);

        $dbconf = $this->getconfig('vister_db');
		if($this->request->isPost()){      
		$id=trim($this->request->param('id'));
		// dump($id);
		$data=Db::connect($dbconf)->table($this->table_dept)->where("id in ($id)")->delete();
        $arr_scheduling = Db::connect($dbconf)->table('view_dept_scheduling')->where("deptid in ($id)")->select();
        if(count($arr_scheduling)>0){
            $arr_scheduling = array_column($arr_scheduling,'id');
            $str_scheduling = implode($arr_scheduling, ",");
            $res=Db::connect($dbconf)->table('scheduling')->where("id in ($str_scheduling)")->delete(); 
        }
		if($data){
			$this->success('部门删除成功！');
		}else{
            $this->success('该部门已删除或不存在！');
        }
		}
    }
    /**获取部门列表**/
    public function getdeptlist(){
        $dept_id = $this->request->param('dept_id');
        $companyid = $this->request->param('companyid');
        // $keyword = $this->request->param('keyword');

        // $where = ''
        $dbconf = $this->getconfig('vister_db');
        $data=Db::connect($dbconf)->table('view_company_dept')->where("companyid =".$companyid)->select();

        return tojson(['code'=>200,'data'=>$data]);
    }

}
